<?php
// 支付功能
namespace app\shop\controller;

use think\Db;
use think\Cache;
use think\Session;
use think\Request;
use think\Exception;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\MemberOrder as MemberOrderModel;
use app\shop\model\MemberOrderAttached as MemberOrderAttachedModel;

class Payment extends Controller
{
    /**
     * 立即支付
     */
    public function index()
    {
        // 获取订单ID/商品订单号 会员ID
        $order_number = Request::instance()->param('order_number');
        $memberId = Session::get('member_id');
        $memberOrders = new MemberOrderModel();
        $memberOrdersAttached = new MemberOrderAttachedModel();


        if (strpos($order_number, ',')) {
            // 多个店铺提交订单
            // 商品价格
            $price = $memberOrders->where(['status' => '0', 'member_id' => $memberId])->where('shop_order_number', 'in', $order_number)->sum('price');
            // 运费
            $freight = $memberOrders->where(['status' => '0', 'member_id' => $memberId])->where('shop_order_number', 'in', $order_number)->sum('freight');
            // 回调信息
            $alipayInformation = $memberOrdersAttached->where('shop_order_number', 'in', $order_number)->field('goods_id')->select();
            // 总订单号
            $order_number = $memberOrders->where('shop_order_number', 'in', $order_number)->value('order_number');

        } else {
            // 单个店铺提交订单
            // 商品价格
            $price = $memberOrders->where(['status' => '0', 'member_id' => $memberId])->where(['shop_order_number' => $order_number])->value('price');
            // 运费
            $freight = $memberOrders->where(['status' => '0', 'member_id' => $memberId])->where(['shop_order_number' => $order_number])->value('freight');
            // 回调信息
            $alipayInformation = $memberOrdersAttached->where(['shop_order_number' => $order_number])->field('goods_id')->select();

        }

        // 订单信息
        $info_time = $memberOrders->where('shop_order_number', 'in', $order_number)->value('create_time');

        // 计算总价
        $total = bcadd($price, $freight, 2);

        // 获取会员余额
        $balance = (new MemberModel)->where(['id' => $memberId])->value('balance');

        $goodIds = "";
        foreach ($alipayInformation as $value) {
            $goodIds .= $value['goods_id'] . ',';
        }
        $goodsStr = rtrim($goodIds, ',');

        // 微信回调信息 阿里回调信息
        $information_wechat = 'pay|' . $memberId . '|' . $goodsStr;
        $information_alipy = 'pay|' . $memberId . '|' . $goodsStr;


        return $this->fetch('', [
            'mate_head'          => '支付页面',
            'order_number'       => $order_number,
            'balance'            => $balance,
            'price'              => $total,
            'goods_id'           => $goodIds,
            'info_time'          => $info_time,
            'information_wechat' => $information_wechat,
            'information_alipy'  => $information_alipy
        ]);
    }


    /**
     * 立即支付（余额）
     */
    public function payment_order()
    {

        if (Request::instance()->isPost()) {

            // 获取参数
            $order_number = Request::instance()->param('order_number');
            $password = Request::instance()->param('password');
            $user_id = Session::get('member_id');

            if (empty($order_number) || empty($user_id)) throw new Exception('not Empty');

            // 判断是否有支付密码
            $unpassword = (new MemberModel)->where('id', $user_id)->value('pay_pass');
            if (empty($unpassword)) return ['code' => 402, 'message' => '您还未设置支付密码'];

            // 判断支付密码是否正确
            if ($unpassword != mcs($password)) return ['code' => 402, 'message' => '支付密码错误'];

            $price = MemberOrderModel::where(['status' => '0', 'member_id' => $user_id])
                ->where(['order_number' => $order_number])
                ->whereOr(['shop_order_number' => $order_number])
                ->sum('price');

            $balance = MemberModel::where(['id' => $user_id])->value('balance');

            if ($balance >= $price) {

                // 启动事务
                Db::startTrans();
                try {

                    // 扣余额
                    $result = Db::name('member')->where(['id' => $user_id])->setDec('balance', $price);

                    if ($result) {

                        // 更新状态
                        Db::name('member_order')->where(['member_id' => $user_id, 'status' => '0'])
                            ->where(['order_number' => $order_number])
                            ->whereOr(['shop_order_number' => $order_number])
                            ->update(['status' => '1', 'way' => '余额支付', 'pay_time' => time()]);


                        // 减少库存
                        // $inventory = Db::name('member_order_attached')
                        //     ->where(['order_number|shop_order_number' => $order_number])
                        //     ->field('goods_id,attr,number,shop_order_number,price')
                        //     ->select();

                        // 消费记录
                        Db::name('member_withdraw')
                            ->insert(['member_id' => $user_id, 'type_id' => '3', 'balance' => ($balance - $price), 'price' => $price, 'way' => '余额支付', 'status' => '1', 'order_number' => $order_number, 'create_time' => time()]);

                        // 首单增加积分
                        // $find = Db::name('integral_record')->where(['member_id' => $user_id, 'type' => '购买'])->value('id');
                        // if (empty($find)) {
                        //
                        //     // 送积分
                        //     Db::name('member')->where(['id' => $user_id])->setInc('integral', Cache::get('web_integral_goods'));
                        //
                        //     // 添加记录
                        //     Db::name('integral_record')->insert(
                        //         [
                        //             'member_id'   => $user_id,
                        //             'type_id'     => '1',
                        //             'type'        => '购买',
                        //             'integral'    => Cache::get('web_integral_goods'),
                        //             'title'       => '（首单）购买商品',
                        //             'create_time' => time()
                        //         ]
                        //     );
                        //
                        // }

                        // 添加积分记录
                        // $mon = [];
                        // $inventory_total = 0;
                        // foreach ($inventory as $item) {
                        //     $inventory_price = ceil(bcmul($item['price'], $item['number'], 2));
                        //     $mon[] = [
                        //         'member_id'   => Session::get('member_id'),
                        //         'type_id'     => '1',
                        //         'type'        => '购买',
                        //         'integral'    => ceil(bcmul($item['price'], $item['number'], 2)),
                        //         // 'title'       => '购买商品订单号为:' . $order_number,
                        //         'title'       => $item['shop_order_number'],
                        //         'create_time' => time()
                        //     ];
                        //     $inventory_total +=$inventory_price;
                        // }
                        //
                        // Db::name('integral_record')->insertAll($mon);
                        // // 购物增加积分
                        //
                        // Db::name('member')->where('id', $user_id)->setInc('integral', $inventory_total);
                        // 提交事务
                        Db::commit();

                        // 赋值url路径
                        // $url = Url::build('member_order/my_order');

                        return ['code' => 200, 'message' => '订单支付成功,正在跳转...'];
                    }

                } catch (\Exception $e) {

                    // 回滚事务
                    Db::rollback();

                    return ['code' => 401, 'message' => '网络繁忙'];
                }

            }

            return ['code' => 402, 'message' => '余额不足'];
        }
        $order_number = Request::instance()->param('order_number');

        return $this->fetch('', [
            'mate_head'    => '余额支付',
            'order_number' => $order_number,
        ]);
    }


}